<template>
  <div class="employees-container">
    <div class="app-container">
      <!-- 通用工具栏组件使用 -->
      <Pagetools>
        <!-- 自定义左侧内容 -->
        <template #slot-left>
          <span>共 19 条记录</span>
        </template>

        <!-- 自定义右侧内容 -->
        <template #slot-right>
          <el-button
            v-power="'imp'"
            type="danger"
            size="small"
            @click="$router.push('/excel')"
          >导入excel</el-button>
          <el-button
            v-power="'exp'"
            type="success"
            size="small"
            @click="excelOutFn"
          >导出excel</el-button>
          <el-button
            type="primary"
            size="small"
            @click="addEmpFn"
          >新增员工</el-button>
        </template>
      </Pagetools>
      <el-card class="box-card">
        <el-table
          border
          :data="employeesList"
          style="width: 100%"
          :default-sort="{ prop: 'mobile', order: 'ascending' }"
        >
          <el-table-column type="index" label="序号" width="50" />
          <el-table-column prop="username" label="姓名" />
          <el-table-column prop="staffPhoto" label="头像">
            <template v-slot="scope">
              <!-- <img class="staffPhoto" :src="scope.row.staffPhoto"> -->
              <ImageHolder :src="scope.row.staffPhoto" />
            </template>
          </el-table-column>
          <el-table-column prop="mobile" label="手机号" sortable />
          <el-table-column prop="workNumber" label="工号" sortable />
          <el-table-column
            prop="formOfEmployment"
            :formatter="formatter"
            label="聘用形式"
          />
          <el-table-column prop="departmentName" label="部门" />
          <el-table-column prop="timeOfEntry" label="入职时间" sortable>
            <template v-slot="scope">
              <span>{{ scope.row.timeOfEntry | timeFilter }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="correctionTime" label="转正时间" sortable>
            <template v-slot="scope">
              <span>{{ scope.row.correctionTime | timeFilter }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="" label="操作" width="150">
            <template v-slot="scope">
              <el-button
                type="text"
                size="small"
                @click="$router.push(`/employees/empInfo?id=${scope.row.id}`)"
              >查看</el-button>
              <el-button
                type="text"
                size="small"
                @click="AssignRoleFn(scope.row.id)"
              >分配角色</el-button>
              <el-button
                type="text"
                size="small"
                @click="delFn(scope.row.id)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页部分 -->
        <el-pagination
          :current-page="query.page"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="query.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </el-card>
      <!-- 对话框部分 -->
      <el-dialog
        title="提示"
        :visible.sync="dialogVisible"
        width="50%"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        @close="clearFn"
      >
        <EmpDialog
          ref="empdialog"
          @close="dialogVisible = false"
          @submitOk="submitSuccessFn"
        />
      </el-dialog>
      <!-- 分配角色弹框 -->
      <el-dialog
        title="分配角色"
        :visible.sync="showAssignRole"
        width="50%"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
      >
        <AssignRole
          v-if="showAssignRole"
          :roleid="useId"
          @close="showAssignRole = false"
        />
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { delEmployessApi, getEmployeesListApi } from '@/api/employees'
import employees from '@/constant/employees'
import EmpDialog from '@/views/employees/empdialog'
import AssignRole from '@/views/employees/assignRole'
import dayjs from 'dayjs'
export default {
  components: { EmpDialog, AssignRole },
  // 过滤器
  filters: {
    timeFilter(val) {
      return dayjs(val).format('YYYY-MM-DD')
    }
  },
  data() {
    return {
      query: {
        page: 1, // 页码
        size: 5 // 每页条数
      },
      employeesList: [], // 员工列表
      total: 0, // 数据总条数
      dialogVisible: false,
      showAssignRole: false,
      useId: ''
    }
  },
  created() {
    this.getEmployeesList()
  },
  methods: {
    // 查询员工列表方法
    async getEmployeesList() {
      const res = await getEmployeesListApi(this.query)
      this.employeesList = res.data.rows
      this.total = res.data.total
    },
    // 每页显示的条数发生改变时触发
    handleSizeChange(val) {
      this.query.pagesize = val
      this.getEmployeesList()
    },
    // 当前页面发生改变时触发
    handleCurrentChange(val) {
      this.query.page = val
      this.getEmployeesList()
    },
    // 格式化内容
    formatter(row, column, cellValue, index) {
      const obj = employees.hireType.find(
        (item) => item.id === Number(cellValue)
      )
      return obj ? obj.value : '未知'
    },
    // 点击删除触发
    async delFn(id) {
      const res = await this.$confirm(
        '此操作将永久删除该员工, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch((err) => err)
      if (res === 'cancel') return this.$message('您已取消删除')
      // 调用接口
      const res1 = await delEmployessApi(id)
      console.log(res1)
      // 提示信息
      this.$message.success(res1.message)
      // 如果员工列表没了,那么就直接去前一页,重新显示
      if (this.employeesList.length === 1) {
        this.query.page > 1 ? this.query.page-- : this.query.page
      }
      // 重新渲染
      this.getEmployeesList()
    },
    // transdata转换数据
    transdata(rows) {
      // 定义映射对象
      const map = {
        id: '编号',
        password: '密码',
        mobile: '手机号',
        username: '姓名',
        timeOfEntry: '入职日期',
        formOfEmployment: '聘用形式',
        correctionTime: '转正日期',
        workNumber: '工号',
        departmentName: '部门',
        staffPhoto: '头像地址'
      }
      // 获取key名对象
      const EkeyArr = Object.keys(rows[0])
      // 通过映射,获取header数组
      const header = EkeyArr.map((item) => {
        return map[item]
      })

      const data = rows.map((item) => {
        return Object.values(item)
      })
      return { header, data }
    },
    // 导出excel
    excelOutFn() {
      // 懒加载方式
      import('@/vendor/Export2Excel').then(async(excel) => {
        // 调用接口,获取最新数据
        const res = await getEmployeesListApi(this.query)
        const excelObj = this.transdata(res.data.rows)
        console.log(excelObj)
        excel.export_json_to_excel({
          header: excelObj.header,
          data: excelObj.data,
          filename: '员工列表',
          autoWidth: true,
          bookType: 'xlsx'
        })
      })
    },
    // 点击新增员工触发
    addEmpFn() {
      this.dialogVisible = true
    },
    // 关闭弹框
    submitSuccessFn() {
      this.dialogVisible = false
      // 重新渲染
      this.getEmployeesList()
    },
    // 关闭后初始化
    clearFn() {
      // 调用子组件中的方法
      this.$refs.empdialog.clearForm()
    },
    // 点击打开分配角色弹框
    AssignRoleFn(id) {
      this.showAssignRole = true
      this.useId = id
    }
  }
}
</script>

<style lang="scss" scoped>
.el-card {
  margin-top: 10px;
}
.el-pagination {
  text-align: center;
  margin-top: 10px;
}
.staffPhoto {
  width: 100px;
  height: 100px;
  border-radius: 50%;
}
</style>
